package com.cloud.common.controller;

import com.cloud.common.bean.ApiReq;
import com.cloud.common.bean.ResultInfo;
import com.cloud.common.context.RequestMapping;
import com.cloud.common.context.RequestMappingManager;
import com.cloud.common.util.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * 接口请求
 */
@Slf4j
@RestController
@ConditionalOnMissingClass("com.cloud.gateway.bean.GatewayInfo")
public class ApiController {
    @Autowired
    private RequestMappingManager requestMappingManager;

    /**
     * 接口请求
     *
     * @return ResultInfo
     */
    @GetMapping("/api/requestData")
    public ResultInfo<List<ApiReq>> requestData() {
        List<ApiReq> mockList = new LinkedList<>();
        Collection<RequestMapping> requestMappings = requestMappingManager.getRequestMappings();
        for (RequestMapping requestMapping : requestMappings) {
            Class requestBodyClass = getRequestBodyClass(requestMapping.getHandlerMethod().getMethod());
            if (requestBodyClass != null) {
                ApiReq apiReq = new ApiReq();
                apiReq.setUri(requestMapping.getMappingUri());
                apiReq.setRequestBody(ObjectUtils.buildInstance(requestBodyClass));
                mockList.add(apiReq);
            }
        }
        return ResultInfo.success().setData(mockList);
    }

    private Class getRequestBodyClass(Method method) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < parameterTypes.length; i++) {
            for (Annotation annotation : annotations[i]) {
                if (annotation instanceof RequestBody) {
                    return parameterTypes[i];
                }
            }
        }
        return null;
    }
}
